﻿using CoachingOrganizer.Logic.Models.Tools.EmotionsPack;
using CoachingOrganizer.WinPhone.UITools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Storage.Streams;

namespace CoachingOrganizer.WinPhone.ViewModels.Tools.EmotionsPack
{
    public class EmotionTraceItemViewModel : ViewModelBase
    {
        private readonly EmotionTraceItemModel _model;
        private ImageSource _bitmap;
        private InMemoryRandomAccessStream _pictureStream;

        public string TraceItemName
        {
            get { return _model.TraceItemName; }
            set { _model.TraceItemName = value; }
        }

        public ImageSource TracePicture
        {
            get { return _bitmap; }
        }

        public EmotionTraceItemViewModel(EmotionTraceItemModel model)
        {
            _model = model;
            UpdatePicture();
        }

        ~EmotionTraceItemViewModel()
        {
            _pictureStream.Dispose();
        }

        private async void UpdatePicture()
        {
            byte[] pictureBytes = _model.TracePicture;
            if (pictureBytes == null)
                return;
            BitmapImage outResult = new BitmapImage();
            _pictureStream = new InMemoryRandomAccessStream();
            await _pictureStream.WriteAsync(pictureBytes.AsBuffer());
            _pictureStream.Seek(0);
            await outResult.SetSourceAsync(_pictureStream);
            _bitmap = outResult;
            BeginInvokeInUIThread(() => OnPropertyChanged(() => TracePicture));
        }
    }
}
